<?php

namespace ChatX\Storage\driver;

use ChatX\Storage\Driver;
use OSS\OssClient;
use OSS\Core\OssException;

class OssAdapter implements Driver
{
    /**
     * @var OssClient|null
     */
    private $client;

    /**
     * {@Liuguobo}
     */
    public function connect(array $config): bool
    {
        try {
            $this->client = new OssClient(
                $config['access_key'] ?? '',
                $config['secret_key'] ?? '',
                $config['endpoint'] ?? ''
            );

            return true;
        } catch (OssException $e) {
            error_log("阿里云OSS连接失败: " . $e->getMessage());
            return false;
        }
    }

    /**
     * {@Liuguobo}
     */
    public function upload(string $bucket, string $objectKey, string $filePath, array $options = [])
    {
        if (!$this->client || !file_exists($filePath)) {
            return false;
        }

        try {
            $options = array_merge([
                OssClient::OSS_CONTENT_TYPE => mime_content_type($filePath)
            ], $options);

            $this->client->uploadFile($bucket, $objectKey, $filePath, $options);

            return [
                'success' => true,
                'object_key' => $objectKey
            ];
        } catch (OssException $e) {
            error_log("阿里云OSS上传失败: " . $e->getMessage());
            return false;
        }
    }

    /**
     * {@Liuguobo}
     */
    public function download(string $bucket, string $objectKey, string $savePath, array $options = []): bool
    {
        if (!$this->client) {
            return false;
        }

        try {
            $this->client->getObject($bucket, $objectKey, $options + ['saveAs' => $savePath]);
            return file_exists($savePath);
        } catch (OssException $e) {
            error_log("阿里云OSS下载失败: " . $e->getMessage());
            return false;
        }
    }

    /**
     * {@Liuguobo}
     */
    public function delete(string $bucket, string $objectKey): bool
    {
        if (!$this->client) {
            return false;
        }

        try {
            $this->client->deleteObject($bucket, $objectKey);
            return true;
        } catch (OssException $e) {
            error_log("阿里云OSS删除失败: " . $e->getMessage());
            return false;
        }
    }

    /**
     * {@Liuguobo}
     */
    public function getInfo(string $bucket, string $objectKey)
    {
        if (!$this->client) {
            return false;
        }

        try {
            $meta = $this->client->getObjectMeta($bucket, $objectKey);

            return [
                'content_type' => $meta['content-type'] ?? '',
                'size' => $meta['content-length'] ?? 0,
                'last_modified' => $meta['last-modified'] ?? null,
                'etag' => $meta['etag'] ?? ''
            ];
        } catch (OssException $e) {
            error_log("阿里云OSS获取信息失败: " . $e->getMessage());
            return false;
        }
    }

    /**
     * {@Liuguobo}
     */
    public function getUrl(string $bucket, string $objectKey, int $expires = 3600)
    {
        if (!$this->client) {
            return false;
        }

        try {
            return $this->client->generatePresignedUrl($bucket, $objectKey, time() + $expires);
        } catch (OssException $e) {
            error_log("阿里云OSS生成URL失败: " . $e->getMessage());
            return false;
        }
    }

    /**
     * {@Liuguobo}
     */
    public function listObjects(string $bucket, array $options = [])
    {
        if (!$this->client) {
            return false;
        }

        try {
            $params = [];

            if (!empty($options['prefix'])) {
                $params['prefix'] = $options['prefix'];
            }

            if (!empty($options['max_keys'])) {
                $params['max-keys'] = $options['max_keys'];
            }

            $result = $this->client->listObjects($bucket, $params);
            // 使用对象方法获取对象列表
            $objects = $result->getObjectList();
            $objectData = [];
            foreach ($objects as $object) {
                $objectData[] = [
                    'key' => $object->getKey(),
                    'last_modified' => $object->getLastModified(),
                    'etag' => $object->getETag(),
                    'size' => $object->getSize(),
                    'storage_class' => $object->getStorageClass()
                ];
            }
            return $objectData;
        } catch (OssException $e) {
            error_log("阿里云OSS列出对象失败: " . $e->getMessage());
            return false;
        }
    }
}